
package com.compuvest.admin.chart;

import com.compuvest.admin.chart.xml.ChartReader;
import com.compuvest.admin.chart.xml.ChartRecord;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import java.util.ArrayList;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/compuvestchart/readXML")
public class ReadXML extends HttpServlet {

    private final static String VERSION = "ReadXML v1.0 2008-13-02";

    private ChartMySQL mysql;

// <editor-fold defaultstate="collapsed" desc="init()">

    @Override
    public void init(ServletConfig config) throws ServletException {
	super.init(config);

	mysql = new ChartMySQL();

	System.out.println("Init: " + VERSION);
    }
// </editor-fold>

//------------------------------------------------
//
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	doPost(request, response);
    }

//------------------------------------------------
//
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        StringBuilder buf = new StringBuilder(5000);
        if("text/xml".equals(request.getContentType())) {

            InputStream in = request.getInputStream();
            ArrayList<ChartRecord> usersList = ChartReader.readChartFromXML(in);

//            BufferedReader r = new BufferedReader(new InputStreamReader(in));
//            String line = null;
//            while ((line = r.readLine()) != null) {
//                buf.append(line);
//            }
            in.close();

//            for(ChartRecord chart : usersList) {
//                buf.append(chart.toString());
//            }
            // store xml
            mysql.updateStock(usersList);
        }
//	System.out.println("---------XML---------");
//	System.out.println(buf.toString());
//	System.out.println("---------XML---------");

	StringBuilder xml = new StringBuilder(500);
        xml.append("<?xml version='1.0' encoding='ISO-8859-1'?>");
	xml.append("<message>");
	xml.append("ok ").append(buf.length());
	xml.append("</message>");

        response.setContentType("text/xml; charset=UTF-8");
        try(PrintWriter out = response.getWriter()) {
            out.print(xml.toString());
        }
    }

    @Override
    public void destroy() {
        mysql = null;
    }
}
